'use strict';
const db = uniCloud.database();
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  console.log('sendCustomerServiceMessage 接收到的参数:', event);
  
  if (!event.uniIdToken) {
    return {
      code: 401,
      msg: '用户未登录'
    };
  }

  const uniIDIns = uniID.createInstance({ context });

  try {
    const { uid: senderId } = await uniIDIns.checkToken(event.uniIdToken);
    if (!senderId) {
      return { code: 401, msg: '用户未登录' };
    }

    const { content, messageType = 'text', imageUrl, sessionId } = event;
    
    if (!content) {
      return { code: 400, msg: '消息内容不能为空' };
    }

    // 获取用户信息
    const userResult = await db.collection('uni-id-users')
      .doc(senderId)
      .field({ nickname: true, avatar_file: true })
      .get();
    
    let senderNickname = '用户';
    let senderAvatar = '';
    
    if (userResult.data && userResult.data.length > 0) {
      const userInfo = userResult.data[0];
      senderNickname = userInfo.nickname || '用户';
      senderAvatar = (userInfo.avatar_file && userInfo.avatar_file.url) ? userInfo.avatar_file.url : '';
    }

    // 构建消息数据，确保与 adminChat 云函数兼容
    const messageData = {
      messageType: messageType,
      senderId: senderId,
      senderNickname: senderNickname,
      senderAvatar: senderAvatar,
      receiverId: 'customer_service', // 发送给客服
      receiverNickname: '客服小助手',
      receiverAvatar: '',
      content: content,
      createTime: new Date(),
      status: 'unread'
    };

    // 如果是图片消息，添加图片URL
    if (messageType === 'image' && imageUrl) {
      messageData.imageUrl = imageUrl;
    }

    console.log('准备插入的消息数据:', messageData);

    // 插入消息到 customer-service-messages 集合
    const result = await db.collection('customer-service-messages').add(messageData);

    console.log('消息插入结果:', result);

    return {
      code: 200,
      msg: '消息发送成功',
      data: {
        _id: result.id,
        sessionId: sessionId || 'default_session',
        ...messageData
      }
    };

  } catch (error) {
    console.error('发送客服消息失败:', error);
    return {
      code: 500,
      msg: '发送消息失败: ' + error.message
    };
  }
};
